# coding=utf-8
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastui import prebuilt_html
from fastapi.responses import HTMLResponse, PlainTextResponse
from fastui.auth import fastapi_auth_exception_handling
from fastui.dev import dev_fastapi_app
from httpx import AsyncClient
from threading import Thread

import multiprocessing
import sys
import os
import uvicorn

project_path = os.path.dirname(__file__)
sys.path.append(project_path)

from ApiAndPage.Main import router as main_router
from ApiAndPage.Reminder import router as reminder_router


@asynccontextmanager
async def lifespan(app_: FastAPI):
    async with AsyncClient() as client:
        app_.state.httpx_client = client
        yield


frontend_reload = '--reload' in sys.argv
if frontend_reload:
    app = dev_fastapi_app(lifespan=lifespan)
else:
    app = FastAPI(lifespan=lifespan)

fastapi_auth_exception_handling(app)

app.include_router(reminder_router, prefix="/api/reminder")
app.include_router(main_router, prefix="/api")


@app.get('/robots.txt', response_class=PlainTextResponse)
async def robots_txt() -> str:
    return 'User-agent: *\nAllow: /'


@app.get('/favicon.ico', status_code=404, response_class=PlainTextResponse)
async def favicon_ico() -> str:
    return 'page not found'


@app.get('/{path:path}')
async def html_landing() -> HTMLResponse:
    return HTMLResponse(prebuilt_html(title='GameWebTools'))


def backServer():
    '''
    后台定时任务
    '''
    pass


if __name__ == '__main__':
    backServer()
    multiprocessing.freeze_support()
    uvicorn.run(app='init:app', host='0.0.0.0', port=80, reload=True)


